#!/bin/bash
###############################################
#This file is configuration managed.          #
#Don't make changes here if you expect them   #
#to stick around.                             #
###############################################
### BEGIN INIT INFO
# Provides:          bedrock
# Required-Start:    networking
# Required-Stop:     networking
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start the Expensify Bedrock jobs/scheduling/cache server.
### END INIT INFO

# Useful environment settings
PATH="/sbin:/bin:/usr/sbin:/usr/bin"
ENV="env -i LANG=C PATH=/usr/local/bin:/usr/bin:/bin"
SSD="/sbin/start-stop-daemon"

# Bedrock-specific settings
NAME="bedrock"
DESC="Expensify Bedrock Server"
BIN="/usr/sbin/bedrock"
PIDFILE="/var/run/$NAME.pid"
BEDROCK_DB_DIR="/var/lib/bedrock"
BEDROCK_DB_PATH="$BEDROCK_DB_DIR/bedrock.db"
SCRIPTNAME="/etc/init.d/$NAME"

# Single node, unknown environment
THISNODE="bedrock"
PRIORITY=200
FLAGS="-v -cache 10001"

if [ -n "$OTHERNODES" ]; then
    FLAGS="-peerList $OTHERNODES"
fi

DAEMON_OPTS="-fork -nodeName $THISNODE -db $BEDROCK_DB_PATH -serverHost 0.0.0.0:8888 -nodeHost 0.0.0.0:8889 -priority $PRIORITY -pidfile $PIDFILE $FLAGS"

if ! [[ -x $BIN ]]; then echo "$1: Job failed! Missing or broken binary file: $BIN" && exit 2; fi
set -e

. /lib/lsb/init-functions

case "$1" in
  start)
    # test for existence of the database files
    if [ ! -d $BEDROCK_DB_DIR ]; then
        log_daemon_msg "DB dir not found, creating dir."
        if ! mkdir $BEDROCK_DB_DIR; then
            log_end_msg 1
        else
            log_end_msg 0
        fi
    fi
    if [ ! -f $BEDROCK_DB_PATH ]; then
        log_daemon_msg "No db found, creating db."
        if ! touch $BEDROCK_DB_PATH; then
            log_end_msg 1
        else
            log_end_msg 0
        fi
    fi
	log_daemon_msg "Starting $DESC" $NAME
	if ! $ENV $SSD --start --quiet\
	--pidfile $PIDFILE --exec $BIN -- $DAEMON_OPTS ; then
            log_end_msg 1
	else
            log_end_msg 0
	fi
    ;;
  stop)
	log_daemon_msg "Stopping $DESC" $NAME
	if $SSD --quiet --stop --oknodo --retry=TERM/30\
	--pidfile $PIDFILE --exec $BIN; then
	    rm -f $PIDFILE
	    log_end_msg 0
	else
	    log_end_msg 1
	fi
	;;
  restart)
	$0 stop
	[ -r  $PIDFILE ] && while pidof bedrock |\
		 grep -q `cat $PIDFILE 2>/dev/null` 2>/dev/null ; do sleep 1; done
	$0 start
	;;
  status)
        status_of_proc -p $PIDFILE $BIN bedrock && exit 0 || exit $?
        ;;
  *)
	echo "Usage: $SCRIPTNAME {start|stop|restart|status}" >&2
	exit 1
	;;
esac

exit 0
